<template>
  <div class="myorder-index">
    <div class="myorder-index-header">
      <van-nav-bar
        title="我的订单"
        left-arrow
        @click-left="$router.go(-1)"
      />
    </div>
    <div class="myorder-index-body">
      <van-tabs v-model="active">
        <van-tab name="all" title="全部">
          <order-list-item v-for="item in filteredList " :key="item.order_id" :items="item" :actives="active"></order-list-item>
        </van-tab>
        <van-tab name="payment" title="待支付">
          <order-list-item v-for="item in filteredList " :key="item.order_id" :items="item" :actives="active"></order-list-item>
        </van-tab>
        <van-tab name="delivery" title="待发货">
          <order-list-item v-for="item in filteredList " :key="item.order_id" :items="item" :actives="active" ></order-list-item>
        </van-tab>
        <van-tab name="received" title="待收货">
          <order-list-item v-for="item in filteredList " :key="item.order_id" :items="item" :actives="active"></order-list-item>
        </van-tab>
        <van-tab name="comment" title="待评价">
          <order-list-item v-for="item in filteredList " :key="item.order_id" :items="item" :actives="active"></order-list-item>
        </van-tab>
      </van-tabs>
    </div>
  </div>
</template>

<script>
import OrderListItem from '@/components/OrderListItem.vue'
import { orderList } from '@/api/order'

export default {
  name: 'MyorderIndex',
  components: {
    OrderListItem
  },
  data () {
    return {
      active: this.$route.query.dataType || 'all',
      page: 1,
      list: [], // 订单列表
      orderIds: [] // 待支付订单id
    }
  },
  computed: {
    loginToken () {
      return this.$store.state.user.loginToken
    },
    filteredList () {
      return this.list.filter(item => item && item?.goods?.length > 0)
    }
  },
  async created () {
    if (this.loginToken) {
      await this.getOrderList()
    }
  },
  methods: {
    // 获取订单列表
    async getOrderList () {
      try {
        // console.log(this.active)
        const response = await orderList(this.active, this.page)
        const listData = response?.data?.list ?? []
        listData.data.forEach((item) => {
          item.total_num = 0
          item.goods.forEach(goods => {
            item.total_num += goods.total_num
          })
        })
        this.list = listData.data
      } catch (err) {
        console.error('获取订单列表失败', err)
      }
    }
  },
  watch: {
    active: {
      immediate: true,
      handler () {
        this.getOrderList()
      }
    }
  }
}
</script>

<style scoped lang="less">
  .myorder-index {
    display: flex;
    flex-direction: column;

    .myorder-index-header { // 头部nav样式
      width: 100%;
      position: fixed;
      top: 0;
      background-color: #fff;
      z-index: 999;
    }
    .myorder-index-body { // 订单列表样式
      margin-top: 46px;
    }
  }
</style>
